import React, { Component } from 'react';
import {
    Image,
    View,
    Dimensions,
    StyleSheet,
    BackHandler,
    ToastAndroid,
    AppRegistry,
    Platform,
    Modal,
    NativeModules
} from 'react-native';
import {
    MapView,
    MapTypes,
    Geolocation
} from 'react-native-baidu-map';
//import nativeModule from 'react-native-xmpush';
var MiPushModule = require('../../MiPushModule');
//var nativeModule = NativeModules.RCTMIPushModule;
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import STRING from '../const_string_zh_CN';
import User from '../net/login.js';
import Toast, {DURATION} from 'react-native-easy-toast';
import { Container, Content, Footer, FooterTab, Button, Icon, Text, Form, Item, Label, Input, Spinner} from 'native-base';
import StudentInfo from '../db/student_table.js';
import UserStateInformation from '../upload/userStateInformation.js';
import UserActionInformation from '../upload/userActionInformation.js';
import DeviceInfo from 'react-native-device-info';
import URL from '../net/url.js';
import BaiduMap from '../upload/baiduMap.js';
const { width, height } = Dimensions.get('window');
const marginTop = Platform.OS === 'ios' ? 20 : 0;
var userState = new UserStateInformation();
var userAction = new UserActionInformation();

const resetAction = NavigationActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({ routeName: 'Tab' })
    ]
});

class page_login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            wait_state: false
        }
    }

    async check_login() {
        this.setState({ wait_state: true });
        const { setLoginState } = this.props;
        let stu = new StudentInfo();
        try {
            await stu.createStudentInfoTable();
            let info = await stu.queryStudentInfo();
            if (info != null && info.length > 0) {
                let item = info.item(0);
                setLoginState({
                    type: 'LoginSuccess',
                    payload: {
                        userName: item.num,
                        realName: item.name,
                        customRole: item.actor,
                    }
                });
                this.setState({ username: item.num });
                //二次登录
                userState.userID = item.num;
                userAction.userID = item.num;

                this.getStateInfo();
                this.getActionInfo();
                return true;
            } else {
                this.setState({ wait_state: false });
                return false;
            }
        } catch (e) {
            console.log("error", e);
        } finally {
            stu.closeStudentInfo();
        }
        this.setState({ wait_state: false });
        return false;
    }

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', function () {
            BackHandler.exitApp();
            return true;
        });


    // nativeModule.setAccount("2016113426");
    // //nativeModule.registerMiPush();

	// nativeModule.setBadgeNumber(0);   // 每次进入app将角标设置为0
    // nativeModule.addEventListener("notification", (notification) => {

    //   console.log("app接收到通知:", notification);
      
    //   // 弹出确认框
    // });

    // nativeModule.getInitialNotification((notification) => {

    //   console.log("app关闭时获取点击通知消息:", notification);
	//   // 弹出确认框
    // });

  }
    

    getStateInfo() {
        let width = Dimensions.get('window').width;
        let height = Dimensions.get('window').height;
        let myPhoneResolution = height + '*' + width;
        userState.myGatherStateInformationTime = userState.getcurrentTime();
        userState.myPhoneResolution = myPhoneResolution;
        userState.myPhoneBrand = DeviceInfo.getManufacturer();
        userState.myOS = DeviceInfo.getSystemName() + DeviceInfo.getSystemVersion();
        userState.myAppVersion = URL.Version;
        userState.uploadStateInformation(userState);
    }

    async getActionInfo() {
        userAction.actionTime = userAction.getcurrentTime();
        userAction.userAction = "login";
        var baidu = new BaiduMap();
        await baidu.componentDidMount();
        userAction.addActionArray(userAction.getUserActionObj(userAction));
        userAction.uploadActionInfo();
    }

    async componentWillMount() {
        if (Platform.OS == 'android') {
            BackHandler.addEventListener('hardwareBackPress', function () {
                BackHandler.exitApp();
                return true;
            });
        }
        const { navigate } = this.props.navigation;
        if (await this.check_login() === true) {
            if (Platform.OS === 'android') {
                this.onPressRegister();
                this.onPressSetUserAccount();
            }
            this.setState({ wait_state: false });
            this.props.navigation.dispatch(resetAction);
        }
        
    // nativeModule.unsetAccount("2016113426");
    // nativeModule.removeEventListener("notification");
  
    }

    async do_login(num, password) {
        let stu = new StudentInfo();
        try {
            let user = new User(num, password);
            this.setState({ wait_state: true })
            let result = await user.do_login();
            console.log(result.model);
            if (result.model) {
                //write db
                stu.insertStudentInfo(result.model.realName, password, num, result.model.customRole);
                return { type: 0, payload: result.model };
            } else if (result.model === undefined) {
                this.setState({ wait_state: false })
                return { type: 1 };
            }
        } catch (e) {
            console.log('eee', e);
        }
    }

    render() {
        const { navigate } = this.props.navigation;
        const { setLoginState } = this.props;//const setLoginState =this.props.setLoginState
        return (

            <Container style={{backgroundColor:'#fff'}}>

                <Modal
                    transparent={true}
                    visible={this.state.wait_state}
                    onRequestClose={() => { }}
                >
                    <Content style={{
                        backgroundColor: 'rgba(0, 0, 0, 0.5)'
                    }}
                        contentContainerStyle={{
                            flex: 1,
                            flexDirection: 'row',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                        <Spinner style={{ alignSelf: 'center', alignItems: 'center' }} />
                    </Content>
                </Modal>
                <Content  >
                  {/* <Image source={require('../images/2.jpeg')}  */}
                    <Image source={require('../images/2-2.png')} 
                        style={{ width: width, height: height / 3 }}
                    />
                    {/* <div style={StyleSheet.flatten(styles.form_style)}> */}
                    <Form style={StyleSheet.flatten(styles.form_style)}>
                        <Item floatingLabel >
                            <Label>{STRING.username}</Label>
                            <Input onChangeText={(v) => { this.setState({ username: v }) }} />
                        </Item>
                        <Item floatingLabel last>
                            <Label>{STRING.password}</Label>
                            <Input secureTextEntry onChangeText={(v) => { this.setState({ password: v }) }} />
                        </Item>
                    </Form>
                    <Button info block  style={StyleSheet.flatten(styles.button_default)} 
                    /* <Button success  */
                        onPress={() => {
                            if (this.state.username.length == 0 || this.state.password.length == 0) {
                                this.refs.toast.show('用户名或密码不能为空',DURATION.LENGTH_LONG);
                                //ToastAndroid.show('用户名或密码不能为空', ToastAndroid.LONG);
                                  
                                this.setState({ wait_state: false });
                            } else {
                                this.do_login(this.state.username, this.state.password).then((res) => {
                                    //用户名和密码不输入时判断
                                    if (res.type === 0) {
                                        //正常匹配，登录成功
                                        this.setState({ wait_state: false });
                                        setLoginState({
                                            type: 'LoginSuccess',
                                            payload: res.payload
                                        });
                                        userState.userID = this.state.username;
                                        userAction.userID = this.state.username;
                                        this.getStateInfo();
                                        this.getActionInfo();

                                        this.props.navigation.dispatch(resetAction);
                                        if (Platform.OS === 'android') {
                                            this.onPressRegister();
                                            this.onPressSetUserAccount();
                                        }//else{
                                            //this.onPressRegisterIOS();
                                           // this.onPressSetAccountIOS();
                                       // }
                                    } else if (res.type === 1) {
                                        //用户名或密码错误
                                        this.refs.toast.show('用户名或密码错误，请重新输入！',DURATION.LENGTH_LONG);
                                        this.setState({ wait_state: false });
                                    } else {
                                        //其它错误
                                        this.refs.toast.show('网络错误，请检查您的网络是否开启！',DURATION.LENGTH_LONG);
                                        this.setState({ wait_state: false });
                                    }
                                }).catch((err) => {
                                    //error
                                    this.refs.toast.show('登录错误，请重新登录！',DURATION.LENGTH_LONG);
                                    this.setState({ wait_state: false });
                                });
                            }

                        }
                        }>
                        <Text>{STRING.login}</Text>
                    </Button>  
                    {/* </div> */}
                </Content>
                <Toast 
                    ref="toast"
                    style={{backgroundColor:'#222'}}
                    position='bottom'
                    positionValue={150}
                    fadeInDuration={750}
                    fadeOutDuration={1000}
                    opacity={0.8}
                />
            </Container>
        );
    }
    onPressRegister() {
        MiPushModule.registerPush();
    }
    onPressSetUserAccount() {
        let student = this.state.username;
        MiPushModule.setUserAccount(student);
    }
  
    // onPressRegisterIOS() {
    //     console.log("--ios注册成功123456-");
    //     nativeModule.registerMiPush();
    // }
    // onPressSetAccountIOS() {
    //     console.log("--ios设置账号2016113426-");
    //     let student = this.state.username;
    //     nativeModule.setAccount(student);
    // }
}


const styles = StyleSheet.create({
    button_default: {
        marginTop: 60,
        width: width / 2,
        alignSelf: 'center',
        // backgroundColor:"#28AB91",
        // border:"#28AB91",
        // color:'#28AB91'
        
    },
    form_style: {
        width: width / 2,
        alignItems: 'center',
        alignSelf: 'center',
    }
});

function mapStateToProps(state) {
    return {}
}

function mapDispatchToProps(dispatch) {
    return {
        setLoginState: (state) => dispatch(state)
    }
}

const PageLogin = connect(
    mapStateToProps,
    mapDispatchToProps
)(page_login)

export default PageLogin;
